package com.hxzy.service.impl;

import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.dto.ProductDTO;
import com.hxzy.dto.ProductSearch;
import com.hxzy.entity.DishFlavor;
import com.hxzy.entity.Merchandise;
import com.hxzy.mapper.MerchandiseMapper;
import com.hxzy.service.DishFlavorService;
import com.hxzy.service.MerchandiseService;
import com.hxzy.util.SSMThreadLocal;
import com.hxzy.vo.AdminLoginVO;
import com.hxzy.vo.DishFlavorsVO;
import com.hxzy.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.*;

/**
 * 商品信息业务逻辑实现
 *
 * @author tonneyyy
 */
@Service
public class MerchandiseServiceImpl extends ServiceImpl<Merchandise,Integer> implements MerchandiseService {

    private MerchandiseMapper merchandiseMapper;

    //口味列表
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    public void setMerchandiseMapper(MerchandiseMapper merchandiseMapper) {
        this.merchandiseMapper = merchandiseMapper;
        super.setMyBatisBaseDao(merchandiseMapper);
    }

    /**
     * 根据商品分类查询商品个数
     * @param mid
     * @return
     */
    @Override
    public int findCountBymid(long mid) {
        return this.merchandiseMapper.findCountBymid(mid);
    }

    /**
     * 商品分页查询
     * @param productSearch
     * @return
     */
    @Override
    public List<ProductVO> search(ProductSearch productSearch) {
        return this.merchandiseMapper.search(productSearch);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public ProductVO findById(Long id) {
        Merchandise merchandise = this.merchandiseMapper.selectByPrimaryKey(id);

        ProductVO  productVO=new ProductVO();
        BeanUtils.copyProperties(merchandise,productVO);

        //查询是否拥有口味列表
        List<DishFlavor> flavorList = this.dishFlavorService.findByDishId(id);
        if(flavorList!=null && flavorList.size()>0){

            List<DishFlavorsVO> dishFlavors=new ArrayList<>();
            //循环数据库的值
            for(DishFlavor dish : flavorList){
                DishFlavorsVO  vo=new DishFlavorsVO();
                //主键
                 vo.setId(dish.getId());
                 vo.setName(dish.getName());
                 vo.setInputVisible(false);
                 vo.setInputValue("");

                 //把["不辣","微辣","中辣","重辣"] 转换为 List<String>
                List<String> stringList = JSONUtil.toList(dish.getValue(), String.class);
                vo.setValue(stringList);

                dishFlavors.add(vo);
            }

            productVO.setDishFlavors(dishFlavors);
        }else{
            // 没有口味列表
            List<DishFlavorsVO> dishFlavors=new ArrayList<>();
            productVO.setDishFlavors(dishFlavors);
        }
        return productVO;
    }

    /**
     * 新增保存
     * @param productDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(@Valid ProductDTO productDTO) { 
        AdminLoginVO  adminLoginVO= SSMThreadLocal.adminLoginVOThreadLocal.get();
        //管理员没有权限修改数据
        if(adminLoginVO.getType()==0){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS);
        }
        
        productDTO.setBid(adminLoginVO.getId());
        
        //新增商品信息
        Merchandise merchandise=new Merchandise();
        BeanUtils.copyProperties(productDTO, merchandise);
        merchandise.setScore(0);
        merchandise.setCreateBy(adminLoginVO.getLoginName());
        merchandise.setCreateTime(new Date());
        //保存
        int count = this.merchandiseMapper.insert(merchandise);
        //新增成功
        if(count>0){
            // 判断是否有口味列表
            List<DishFlavorsVO> dishFlavors = productDTO.getDishFlavors();
            if(dishFlavors!=null && dishFlavors.size()>0){
                for(DishFlavorsVO item: dishFlavors){
                    DishFlavor dishFlavor=new DishFlavor();
                    //商品id
                    dishFlavor.setDishId( merchandise.getId());
                    dishFlavor.setName( item.getName());
                    dishFlavor.setIsDeleted(0);
                    //List<String>转换成["",""]   把javalist转换成json数组字符串
                    String value=JSONUtil.toJsonStr( item.getValue());
                    dishFlavor.setValue(value);
                    dishFlavor.setCreateBy(adminLoginVO.getLoginName());
                    dishFlavor.setCreateTime(new Date());
                    //新增口味列表
                    this.dishFlavorService.insert(dishFlavor);
                }
            }
        }
        return count;
    }

    @Override
    public int update(@Valid ProductDTO productDTO) {
        AdminLoginVO  adminLoginVO= SSMThreadLocal.adminLoginVOThreadLocal.get();
        //管理员没有权限修改数据
        if(adminLoginVO.getType()==0){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS);
        }
        productDTO.setBid(adminLoginVO.getId());
        //新增商品信息
        Merchandise dbMerchandise=this.merchandiseMapper.selectByPrimaryKey(productDTO.getId());
        BeanUtils.copyProperties(productDTO, dbMerchandise,"createTime","createBy","score");

        dbMerchandise.setUpdateBy(adminLoginVO.getLoginName());
        dbMerchandise.setUpdateTime(new Date());
        //保存
        int count = this.merchandiseMapper.updateByPrimaryKeySelective(dbMerchandise);

        if(count>0){
            // 先删除口味列中的所有数据 dish_flavor  where dish_id=?
            this.dishFlavorService.deleteByDishId(productDTO.getId());

            // 判断是否有口味列表
            List<DishFlavorsVO> dishFlavors = productDTO.getDishFlavors();
            if(dishFlavors!=null && dishFlavors.size()>0){
                for(DishFlavorsVO item: dishFlavors){
                    DishFlavor dishFlavor=new DishFlavor();
                    //商品id
                    dishFlavor.setDishId( productDTO.getId());
                    dishFlavor.setName( item.getName());
                    dishFlavor.setIsDeleted(0);
                    //List<String>转换成["",""]   把javalist转换成json数组字符串
                    String value=JSONUtil.toJsonStr( item.getValue());
                    dishFlavor.setValue(value);
                    dishFlavor.setCreateBy(adminLoginVO.getLoginName());
                    dishFlavor.setCreateTime(new Date());
                    //新增口味列表
                    this.dishFlavorService.insert(dishFlavor);
                }
            }
        }
        return count;
    }

    /**
     * 获取某个商家的菜品分类对应的菜品
     * @param categoryId
     * @param bid
     * @return
     */
    @Override
    public List<ProductVO> findProdeuctByCategoryIdAndbid(Long categoryId, Long bid) {
        List<Merchandise> arr= this.merchandiseMapper.findProdeuctByCategoryIdAndbid(categoryId,bid);

        List<ProductVO> arrList=new ArrayList<>();

        for(Merchandise item: arr){
            ProductVO  productVO=new ProductVO();
            BeanUtils.copyProperties(item,productVO);

            //查询是否拥有口味列表
            List<DishFlavor> flavorList = this.dishFlavorService.findByDishId(item.getId());
            if(flavorList!=null && flavorList.size()>0){
                List<DishFlavorsVO> dishFlavors=new ArrayList<>();
                //循环数据库的值
                for(DishFlavor dish : flavorList){
                    DishFlavorsVO  vo=new DishFlavorsVO();
                    //主键
                    vo.setId(dish.getId());
                    vo.setName(dish.getName());
                    vo.setInputVisible(false);
                    vo.setInputValue("");
                    //把["不辣","微辣","中辣","重辣"] 转换为 List<String>
                    List<String> stringList = JSONUtil.toList(dish.getValue(), String.class);
                    vo.setValue(stringList);
                    dishFlavors.add(vo);
                }
                productVO.setDishFlavors(dishFlavors);
            }else{
                // 没有口味列表
                List<DishFlavorsVO> dishFlavors=new ArrayList<>();
                productVO.setDishFlavors(dishFlavors);
            }
            arrList.add(productVO);
        }
        return arrList;
    }
}